package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.ResultVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /*登录---获取验证码*/
    public void sendMsg(String phone) {
        //生成验证码
        //String code = RandomStringUtils.randomNumeric(6);
        //发送短信
        //smsTemplate.sendSms(phone, code);
        String code = "123456";
        //将验证码保存到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }


    /*登录---验证码校验*/
    public Map loginVerification(String phone, String code) {
        //从redis中获取保存的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //校验验证码
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效,抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //通过手机号判断是否新用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //新用户则创建
        if (user == null) {
            //先注册环信
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //拼接环信用户id
            String hxUser = "hx"+user.getId();
            //注册环信
            Boolean result = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            //注册成功则更新用户信息
            if (result){
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }


        }
        //通过JWT生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /*修改手机号 - 2 校验验证码*/
    public ResultVo checkVerificationCode(String code) {
        //获取当前用户目前的手机号
        String phone = UserHolder.getMobile();
        //从redis中获取保存的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //校验验证码
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效,抛出异常
            throw new BusinessException(ErrorResult.loginError());
        }else {
            //删除验证码
            redisTemplate.delete("CHECK_CODE_" + phone);
        }
        ResultVo vo=new ResultVo();
        vo.setVerification(true);
        return vo;
    }

    /*修改手机号 - 3 保存*/
    public void updatePhone(String phone) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api修改手机号
        User user=new User();
        user.setId(userId);
        user.setMobile(phone);
        userApi.updatePhone(user);
    }
}
